#! /usr/bin/env python
# encoding: utf-8

"""Adapter to use Jinja2 as template system for Spyro.
"""

import logging

from jinja2 import Environment, FileSystemLoader

from spyro.config.register import Register

log = logging.getLogger(__name__)
env = None

class Template:
    """An abstraction over Jinja2.
    This is done mainly for future support via a unique interface to other
    template systems.
    """

    def __init__(self, template_name, translations):
        """It will search the files in the directory defined in the
        configuration file ('views' by defalut).
        """

        global env
        config = Register.i18n
        template_dir = Register.templates['root']

        if env is None:
            env = Environment(loader=FileSystemLoader(template_dir),
                              autoescape=True,
                              extensions=['jinja2.ext.i18n'])

        if translations is not None:
            env.install_gettext_translations(translations)

        self.file = template_name

    def render(self, ctx):
        """Returns the rendered webpage.
        """

        global env
        return env.get_template(self.file).render(ctx)
